package com.googlecode.afx.view.binding;

import java.util.Map;

import com.googlecode.afx.view.NodeWrapper;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Task;
import javafx.scene.Node;

public class DatabindingUtils {

	/**
	 * Checks, whether data binding is supported for the given <tt>node</tt>.
	 * 
	 * @param node
	 * @return
	 */
	public static boolean supportsPrimaryValue(Node node) {
		return NodeWrapper.supportsPrimaryValue(node.getClass());
	}

	/**
	 * Extracts all values from nodes that have an "id" and and that
	 * support a primary value.
	 * 
	 * @param wrapper
	 * @param path
	 * @param node
	 */
	public static Map<String, Object> extractValues(Node node) {
		ValueExtractingNodeHandler handler = new ValueExtractingNodeHandler();
		NodeWrapper.traverse(node, handler);
		return handler.getAllValues();
	}
	
	/**
	 * Binds the <tt>progressProperty</tt> of <tt>javafx.concurrent.Task</tt> to the given <tt>progressBarNode</tt>.
	 *  
	 * @param task
	 * @param progressBarNode
	 */
	public static void bindTaskToProgressProperty(Task<?> task, Node progressBarNode) {
		NodeWrapper wrapper = new NodeWrapper(progressBarNode);
		DoubleProperty property = (DoubleProperty) wrapper.getProperty(NodeWrapper.PROP_PROGRESSPROPERTY);
		property.unbind();
		property.set(0.0f);
		property.bind(task.progressProperty()); 
	}

	/**
	 * Unbinds the given <tt>progressBarNode</tt>.
	 *  
	 * @param progressBarNode
	 */
	public static void unbindProgressProperty(Node progressBarNode) {
		NodeWrapper wrapper = new NodeWrapper(progressBarNode);
		DoubleProperty property = (DoubleProperty) wrapper.getProperty(NodeWrapper.PROP_PROGRESSPROPERTY);
		property.unbind();
		property.set(0.0f);
	}
	
	
	/**
	 * Binds the <tt>messageProperty</tt> of <tt>javafx.concurrent.Task</tt> to the given <tt>messageNode</tt>.
	 * 
	 * @param task
	 * @param messageNode
	 */
	public static void bindTaskToMessageProperty(Task<?> task, Node messageNode) {
		NodeWrapper wrapper = new NodeWrapper(messageNode);
		StringProperty property = (StringProperty) wrapper.getProperty(NodeWrapper.PROP_TEXTPROPERTY);
		property.unbind();
		property.set("");
		property.bind(task.messageProperty());
	}

	/**
	 * Unbinds the given <tt>messageNode</tt>.
	 *  
	 * @param messageNode
	 */
	public static void unbindMessageProperty(Node messageNode) {
		NodeWrapper wrapper = new NodeWrapper(messageNode);
		StringProperty property = (StringProperty) wrapper.getProperty(NodeWrapper.PROP_TEXTPROPERTY);
		property.unbind();
		property.set("");
	}
	
	
}
